
const isEqual = (current, next, preKeys = []) => {
  return preKeys.every(key => current[key] === next[key])
}

/**
 * @description 合并行
 * @param rows 表格数组
 * @param key 列字段
 * @returns {Array}
 */
export const mergeRows = (rows, key, preKeys) => {
  rows[0].rowSpan = 1;
  let idx = 0;
  return rows.slice(1).reduce(
    (mergedRows, item, index) => {
      if (item[key] === mergedRows[idx][key] && isEqual(item, mergedRows[idx], preKeys)) {
        mergedRows[idx].rowSpan++;
        item.colSpan = 0;
      } else {
        item.rowSpan = 1;
        item.colSpan = 1;
        idx = index + 1;
      }
      return [...mergedRows, item];
    },
    [rows[0]]
  );
};
/**
 * @description 合并表格
 * @param rows 表格数组
 * @param keys 列字段数组
 * @returns {Array}
 */
export const tableMerge = (rows, keys) => {
  const spanConfig = {}
  keys.forEach((key, index) => {
    const preKeys = keys.slice(0, index)
    const arr = mergeRows(rows, key, preKeys).map(item => {
      const { rowSpan, colSpan } = item
      delete item.rowSpan
      delete item.colSpan
      return {
        rowSpan,
        colSpan
      }
    })
    spanConfig[key] = arr
  })
  rows.forEach((item, index) => {
    item.spanConfig = Object.keys(spanConfig).reduce((cur, nextKey) => {
      const value = spanConfig[nextKey]
      cur[nextKey] = value[index]
      return cur
    }, {})
  })
  return rows
}
/**
 * @description 获取单元格span配置
 * @param row 表格数组
 * @param key 列字段
 * @returns {Object}
 */
export const getCellSpan = (row, key) => {
  const config = row.spanConfig
  if (!config || !config[key]) return {}
  return config[key]
}

/**
 * @description 列字段值相等重新排序
 * @param arr 表格数组
 * @param key 列字段
 * @returns {Object}
 */
export const sortRows = (arr = [], key) => {
  const obj = {}
  arr.forEach(item => {
    if (!obj[item[key]]) {
      obj[item[key]] = []
    }
    obj[item[key]].push(item)
  })
  const mapper = {}
  const list = Object.keys(obj).reduce((cur, key) => {
    const value = obj[key]
    mapper[key] = value.length
    return [...cur, ...value]
  }, [])
  return {
    list,
    mapper
  }
}